package Dao.Impl;

import Bean.User;
import Dao.BasicDao;
import Dao.UserDao;
import Utils.DBHelp;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

public class UserDaoImpl extends BasicDao implements UserDao {
    private static int id = 1;
    public int getId(){
        return id++;
    }
    public User getUser(String username){
        String sql = "select * from user where name = ?;";
        QueryRunner queryRunner = new QueryRunner();
        User query = null;
        try {
            query = queryRunner.query(DBHelp.getConnection(), sql, new BeanHandler<>(User.class), username);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
        }
        return query;
    }
    public int saveUser(User user){
        String sql ="insert into user values (name,MD5(passWord),email),(?,?,?);";
        QueryRunner queryRunner = new QueryRunner();
        int count = 0;
        try {
            count = queryRunner.update(DBHelp.getConnection(),sql,user.getName(),user.getPassWord(),user.getEmail());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
        }
        return count;
    }
    public static String getMD5passWord(String passWord){
        String sql = "select MD5(?);";
        QueryRunner queryRunner = new QueryRunner();
        String Word = " ";
        try {
            Word = (String)queryRunner.query(DBHelp.getConnection(), sql, new ScalarHandler(), passWord);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
        }
        return Word;
    }




}
